package com.mab.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.mab.mall.auth.feign.MemberFeignService;
import com.mab.mall.auth.feign.ThirdPartFeignService;
import com.mab.mall.auth.vo.LoginVo;
import com.mab.mall.auth.vo.UserRegisterVo;
import com.msb.common.constant.AuthConstant;
import com.msb.common.constant.SMSConstant;
import com.msb.common.exception.BizCodeEnum;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone){
        //防止60s重新发送
        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PREFIX + phone);
        if(redisCode != null && !"".equals(redisCode.toString())){
            long l = Long.parseLong(redisCode.toString().split("_")[1]);
            if(System.currentTimeMillis() - l <= 60000){
                return R.error(BizCodeEnum.VALID_SMS_EXCEPTION.getCode(),BizCodeEnum.VALID_SMS_EXCEPTION.getMsg());
            }
        }
        //生成随机的验证码 -->把生成的存再redis中
//        String code = UUID.randomUUID().toString().substring(0, 4);
        Random random = new Random();
        int codeInt = random.nextInt(9000) + 1000;
        String code = codeInt+"";
        thirdPartFeignService.sendSmsCode(phone,code);
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PREFIX+phone,code+"_"+System.currentTimeMillis(),60, TimeUnit.SECONDS);

        return R.ok();
    }

    @PostMapping("/sms/register")
    public  String register(@Valid UserRegisterVo vo, BindingResult result, Model model){
        Map<String,String> map = new HashMap<>();
        if(result.hasErrors()){
            //表示提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError :fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            model.addAttribute("error",map);
            return "/register";
        }else{
            //验证码是否正确
            //防止60s重新发送
            Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PREFIX + vo.getPhone());
            if(redisCode != null && !"".equals(redisCode.toString())){
                long l = Long.parseLong(redisCode.toString().split("_")[1]);
                String code = redisCode.toString().split("_")[0];
                if(!code.equals(vo.getCode())){
                    //说明验证码不正确
                    map.put("code","验证码不正确");
                    model.addAttribute("error",map);
                    return "/register";
                }else{
                    if(System.currentTimeMillis() - l > 60000){
                        //说明验证码不正确
                        map.put("code","验证码已失效，请重新获取");
                        model.addAttribute("error",map);
                        return "/register";
                    }else{
                        //验证码正确，删除验证码
                        redisTemplate.delete(SMSConstant.SMS_CODE_PREFIX + vo.getPhone());
                        //远程调用，完成服务器
                        R r = memberFeignService.register(vo);
                        if(r.getCode() == 0){
                            //表示数据合法
                            return "redirect:/login.html";
                        }else{
                            map.put("msg",r.getCode()+":"+r.getMsg(r.getCode()));
                            model.addAttribute("error",map);
                            return "/register";
                        }
                    }
                }
            }else{
                map.put("code","验证码已失效，请重新获取");
                model.addAttribute("error",map);
                return "/register";
            }
        }
    }

    @PostMapping("/login")
    public String login(LoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0){
            String entityJson = (String) login.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            return "redirect:http://localhost:8040/home";
        }
        redirectAttributes.addAttribute("error",login.get("msg"));
        //表示登录失败
        return "/login";

    }


}
